package xuegao.study.mall.oauth2.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import xuegao.study.mall.common.api.CommonResult;

/**
 * 全局异常拦截器,处理全局异常
 */
@ControllerAdvice
public class GlobalException {

    private Logger log = LoggerFactory.getLogger(GlobalException.class);

    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public CommonResult handleRuntimeException(RuntimeException e) {
        log.error("method invoke error", e);
        // 此处针对spring security中的异常进行单独处理,否则spring security中的异常过滤器ExceptionTranslationFilter无法捕获到一些异常,
        // 导致它的处理逻辑出现错误
        if (e instanceof AuthenticationException) {
            throw e;
        }
        String errMsg = e.getMessage();
        return CommonResult.failed(errMsg);
    }
}
